from django.shortcuts import render
# from PIL import Imade,ImageDraw,ImageFont

# Create your views here.
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse


def index(request):
    html = ' 智慧园! <br/><img src="/static/img.py" alt="no" width="100px" height="80px">'
    return HttpResponse(html, '这是我的智慧园')


def web(request):
    return render(request, 'web.html')


def toAddNew(request):
    return render(request, 'newuser.html')


def doCheckUid(request):
    ps = userinfo.objects.filter(uid=request.GET['uid'])
    if ps.count()==0:
        msg='ID 可用'
    else:
        msg='ID 已占有'
    return HttpResponse(msg, content_type="text/text;charset=utf-8")


def returnCheckCode(requset):
    return HttpResponse(requset.session['randomcode'], content_type="text/text;charset=utf-8")


def doAddNew(requset):
    try:
        nuid = requset.GET['uid']
        pwd = requset.GET['pwd']
        nemail = requset.GET['email']
        user=userinfo(uid=nuid,password=pwd,email=nemail)
        user.save()
        msg="已成功完成注册！"
        return HttpResponse(msg, content_type="text/text;charset=utf-8")
    except Exception as e:
        msg="意外出错: %s" % e
        return HttpResponse(msg, content_type="text/text;charset=utf-8")

def createImg(request):
    img = Image.new(mode="RGB", size=(160, 30), color=(100, 1001, 100))
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(font="arial.ttf",size=24)
    code = ''
    for i in range(5):
        c = getRandomChar()
        draw.text((10+30*i, 2),text = c,fill = (255,255,255),font=font)
        code+=c
    request.session[' randomcode '] = code
    f = open("test.png", 'wb')
    img.save(f, format="png")
    f.close()
    return


def getRandomChar():
    unm = str(randint(0, 9))
    lower = chr(randint(97, 122))
    upper = chr(randint(65, 90))
    char = choice([unm, lower, upper])
    return char



